/**
 * @program: findfiledemo
 * @author: Ding Houwen
 * @create: 2019-08-12 11:48
 **/

package com.example.findfiledemo.controller;

import com.example.findfiledemo.entiy.ResponseObj;
import com.example.findfiledemo.service.AnyQService;
import com.example.findfiledemo.service.VideoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@Api(value = "VideoRecognitionController", description = "语音识别Controller")
@Controller
@RequestMapping("/videore")
@CrossOrigin(allowedHeaders = "*", allowCredentials = "true")
public class VideoRecognitionController {

    @Autowired
    private VideoService videoService;
    @Autowired
    private AnyQService anyQService;

    @ApiOperation(value = "语音识别转文字", notes = "对PCM（无压缩）")
    @PostMapping(value = "/findfile")
    @ResponseBody
    public ResponseObj audioToText(@RequestParam("audioData") MultipartFile request) throws Exception {
        byte[] param = request.getBytes();
        ResponseObj obj = new ResponseObj();
        Map map = new HashMap();
        JSONObject result = videoService.getResult(param);
        String no = String.valueOf( result.get("err_no"));
        switch (no) {
            case "3308":
                // 音频过长
                obj.setCode("3308");
                map.put("msg", "您输入的语音时间太长啦，我们不能识别");
                break;
            case "3301":
                // 音频质量过差
                obj.setCode("3301");
                map.put("msg", "您说什么？我没听清楚");
                break;
            case "3314":
                // 音频长度过短
                obj.setCode("3314");
                map.put("msg", "您输入的语音太短啦");
                break;
            case "0":
                // 正常状态
                obj.setCode("200");
                JSONArray jArray  = (JSONArray)result.get("result");
                String str = jArray.getString(0);
                if (str.startsWith("[\"") && str.endsWith("\"]")) {
                    str = str.substring(2, result.length() - 3);
                }
                map.put("msg", str.substring(0,str.length()-1));
                break;
            default:
                obj.setCode("500");
                map.put("msg", "未知的错误");
                // 其他状态，不一一列举
        }
        obj.setData(map);
        return obj;
//        if(result.startsWith("[\"") && result.endsWith("\"]")){
//            result = result.substring(2,result.length()-3);
//        };
//        String anyqResult = anyQService.question(result);
//        System.out.println("anyq结果："+anyqResult);

    }

}

